//index.js
//获取应用实例
const app = getApp();
var timer = '';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    sign: "",
    share_img: "",
    number: '',
    imgurl: app.urlimg,
    //用户进入
    state: '',// 0为用户第一次进入   1为用户第二次进入  2为好友进入  3为瓜分成功  4为瓜分失败 5为好友第二次进入
    //活动规则
    shortcut: true,
    //红包显示(首页)
    receive_hidden: '',
    //刮分金额
    Scrape_money: true,
    //推荐显示内容
    conment_box: '',
    img: 'https://lteimg1.camel.com.cn/upload/wx/yuanjiaojuxing.png',
    smallpack: [
      { money: '50', imgs: '', },
    ],
    background_img: '',
    total_money: '',
    invite: true,
    money: '50',
    time: '23:59:59',
    cash: '',
    is_part: '',
    url: '',
    userList: "",
    lucks: "",
    //推荐商品
    goodsList: "",
    end_time: "",
    images: {},
    shu: "",
  },
  //规则
  rule_click: function () {
    var that = this;
    var shortcut = that.data.shortcut;
    if (shortcut) {
      shortcut = false;
    } else {
      shortcut = true;
    }
    that.setData({ shortcut: shortcut, })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options);
  
    app.app_load(load_fn);

    function load_fn() {
      if (options.sign == undefined) {
        options.sign = '';
      }
      console.log(wx.getStorageSync('token_key'));
      wx.request({
        url: app.url + 'api_open_luck/index',
        data: {
          id: options.id,
          sign: options.sign,
        },
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('token_key')
        }, success: function (json) {
          console.log(json.data.result);
          console.log(json.data.message);
          if (json.data.message == '活动已过期！') {
            that.setData({
              receive_hidden: true,
              Scrape_money: true,
              conment_box: true,
            })
            wx.showModal({
              title: '提示',
              content: '活动已过期！',
              success: function (res) {
                setTimeout(function () {
                  wx.reLaunch({ url: '/pages/index/index' })
                }, 100)
              }
            })
          } else {
            var state = json.data.result.state;
            console.log('状态为：' + state);
            //获取用户个数
            var user_list = json.data.result.user_list;

            if (user_list != undefined && json.data.result.state != 3 && json.data.result.state != 6 && json.data.result.number > user_list.length) {
              var user_num = json.data.result.number - user_list.length;
              for (var i = 0; i < user_num; i++) {
                user_list.push({ captain: "", coupon_id: '', head_ico: "", state: "", user_id: "" });
              }
            }

            console.log(user_list);
            that.setData({
              options_id: options.id,
              title: json.data.result.title,
              shu: json.data.result.shu,//缺少的人数
              state: json.data.result.state, // 状态
              background_img: json.data.result.background_img, // 背景图
              total_money: json.data.result.total_money, // 红包价格
              info: json.data.result.info, // 活动规则
              userList: user_list, //用户列表
              goodsList: json.data.result.goods_list, // 商品列表
              sign: json.data.result.sign, // 标识
              share_img: json.data.result.share_img,  // 分享的图片
              cash: json.data.result.cash, // 红包金额
              is_part: json.data.result.is_part, // 
              url: json.data.result.url, // 跳转链接
              end_time: json.data.result.end_time, // 结束时间
              goods_nav_img: json.data.result.goods_nav_img,
              money_title: json.data.result.money_title,
              type: json.data.result.type,
            })

            console.log('id为：' + that.data.options_id);

            //红包显示(首页)
            var receive_hidden = '',
              //刮分金额
              Scrape_money = '',
              //推荐显示内容
              conment_box = '';
            if (state == 0) {//用户第一次进入
              receive_hidden = false;
              Scrape_money = true;
              conment_box = true;
            } else if (state == 1) {//用户第二次进入
              receive_hidden = true;
              Scrape_money = false;
              conment_box = false;
            } else if (state == 3 || state == 4) {//瓜分成功  瓜分失败
              receive_hidden = true;
              Scrape_money = true;
              conment_box = false;
            } else if (state == 2 || state == 5) {//好友第一次进入  好友第二次进入
              receive_hidden = true;
              Scrape_money = false;
              conment_box = false;
            } else if (state == 6) {//分刮人数满足，其他人进入时显示的样式
              receive_hidden = true;
              Scrape_money = true;
              conment_box = false;
            }

            //倒计时时间戳
            var time = json.data.result.time;

            if (state != 3 && state != 4 && state != 6) {
              end_time(time, that);
            } else {
              clearInterval(timer);
              timer = '';
            }

            if (state == 1 || state == 5) {
              that.setData({
                invite: false,
              })
            }

            //判断最佳手气
            if (state == 3) {
              var lucks = that.data.lucks;
              var all_dol = [];
              for (var i = 0; i < lucks.length; i++) {
                all_dol.push(lucks[i].dol);
              }
              that.setData({
                invite: max_dol(all_dol),
              })
              function max_dol(all_num) {
                var max_index = all_num[0];
                for (var i = 1; i < all_num.length; i++) {
                  if (parseInt(all_num[i]) > parseInt(max_index)) {
                    max_index = all_num[i];
                  }
                }
                console.log(max_index);
                return max_index;
              }
            }

            that.setData({
              receive_hidden: receive_hidden,
              // Scrape_money: Scrape_money,
              Scrape_money: false,
              conment_box: conment_box,
              time: json.data.result.time, // 倒计时
            })
          }


        }
      })
    }


  },
  //导航栏图片大小
  imageLoad: function (e) {
    var $width = e.detail.width,    //获取图片真实宽度
      $height = e.detail.height,
      ratio = $width / $height;    //图片的真实宽高比例
    var viewWidth = 718,           //设置图片显示宽度，左右留有16rpx边距
      viewHeight = 718 / ratio;    //计算的高度值
    var image = this.data.images;
    //将图片的datadata-index作为image对象的key,然后存储图片的宽高值
    image = {
      width: viewWidth,
      height: viewHeight
    }
    this.setData({
      images: image
    })
  },
  //红包领取按钮
  receive_click: function () {
    var that = this;
    console.log(that.data.options_id);

    wx.request({
      url: app.url + 'api_open_luck/open_luck_user_add',
      data: {
        id: that.data.options_id,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        console.log(json);
        if (json.data.done){
          var options = {};
          options.id = that.data.options_id;
          that.onLoad(options);
        }else{
          app.apperror(json);
          that.setData({
            Scrape_money: true,
          })
        }
      }
    })
    var animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 1000,
      timingFunction: "ease",
      delay: 0
    });
    that.animation = animation;
    animation.opacity(0).step();
    that.setData({
      animation01: animation.export(),
      Scrape_money: false,
    })
    setTimeout(function () {
      that.setData({
        receive_hidden: true,
        conment_box: false,
      })
    }, 1000)
  },
  // 关闭弹出的瓜分奖金窗口
  Scrape_money_click: function () {
    this.setData({
      Scrape_money: true,
    })
  },
  //一起拆红包
  open_red: function () {
    var that = this;
    console.log('id为：' + that.data.options_id);
    wx.request({
      url: app.url + 'api_open_luck/open_luck_user_add',
      data: {
        id: that.data.options_id,
        sign: that.data.sign,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        console.log(json);
        if (json.data.done) {
          that.setData({
            Scrape_money: false,
            invite: false,
          })
          var options = {};
          options.id = that.data.options_id;
          options.sign = that.data.sign;
          that.onLoad(options);
        } else {
          wx.showModal({
            title: '提示',
            content: json.data.message,
          })
        }
      }
    })
  },
  //拆一个新红包
  new_red_bag: function () {
    var that = this;
    console.log('拆一个新红包,重新进入页面，state 状态改为0');
    this.setData({
      state: 0,
    })
    var options = {};
    options.id = that.data.options_id;
    that.onLoad(options);
  },
  // 立即使用
  go_home: function () {
    var that = this;
    console.log('进入商城首页');
    console.log(that.data.url);
    wx.reLaunch({
      url: that.data.url,
    })
  },
  //进入商品详情页
  toDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/index/detail/index?id=' + id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    if (this.state != 3 && this.state != 4) {
      console.log(55555);
      timer = setInterval(function () {
        end_time(that.data.time, that);
      }, 1000)
    } else {
      // clearInterval(timer);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(timer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    var share_img = that.data.share_img;
    var imageUrl = that.data.imgurl + share_img.substring(1);
    console.log(that.data.sign);
    // var imageUrl = "http://www.ltwx.com/" + share_img.substring(1);// 测试 要删掉
    console.log(imageUrl);
    return {
      imageUrl: imageUrl,
      title: that.data.title, // 标题
      path: '/pages/index/detail/open_red_bag/index?id=' + that.data.options_id + '&sign=' + that.data.sign, // 分享后点击页面链接
      success: function (res) {
        // 已发送邀请，发送微信群，拆开红包概率达98 %
      }
    }
  },
  //   商品推荐 加载
  goodsList: function () {
    var that = this;
    wx.request({
      url: app.url + "?controller=api_coupon&action=recommend",
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (data) {

        that.setData({
          goodsList: data.data.result,
          imgUrl: app.urlimg
        });
      }
    })
  },
})

//倒计时函数
function end_time(time, that) {
  if (time != '') {
    time--;
    var h = Math.floor(time / 60 / 60 % 24);
    var m = Math.floor(time / 60 % 60);
    var s = Math.floor(time % 60);
    var end_tt = h + ':' + m + ':' + s;
    // console.log('执行倒计时');
    // console.log(time);
    that.setData({
      time: time,
      time_text: end_tt,
    })
  } else {
    clearInterval(timer);
  }
}
